<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue';
import Taro from '@tarojs/taro';
import { useAuthStore } from '@/store';
import { localStg } from '@/utils';
import { updateUser } from '@/service/api';
import { getRequestUrl, showErrorMsg, showSuccessMsg } from '@/service/request/helpers';

const authStore = useAuthStore();
const userInfo = ref<Auth.UserInfo>(authStore.getUserInfo());

const toastState = {
  state: reactive({
    show: false,
    msg: '',
    type: 'text'
  }),
  methods: {
    cellClick(type: string, msg: string) {
      toastState.state.show = true;
      toastState.state.type = type;
      toastState.state.msg = msg;
    }
  }
};

const userState = {
  state: reactive({
    show: false,
    submitType: '',
    inputLabel: '',
    value: ''
  }),
  methods: {
    onClosed() {
      userState.state.show = false;
      userState.state.submitType = '';
      userState.state.inputLabel = '';
      userState.state.value = '';
    },
    onUpdate(submitType: string) {
      userState.state.submitType = submitType;
      if (submitType === 'name') {
        userState.state.inputLabel = '姓名';
      } else if (submitType === 'nickname') {
        userState.state.inputLabel = '昵称';
      } else {
        userState.state.inputLabel = '';
      }
      userState.state.show = true;
    },
    onSubmit() {
      const user = {
        id: userInfo.value.id,
        name: userInfo.value.name,
        username: userInfo.value.username,
        nickname: userInfo.value.nickname,
        phoneNumber: userInfo.value.phoneNumber
      } as Auth.UserInfo;
      userState.state.show = false;
      if (userState.state.submitType === 'name') {
        user.name = userState.state.value;
      } else if (userState.state.submitType === 'nickname') {
        user.nickname = userState.state.value;
      }
      updateUser(user).then(() => {
        userInfo.value.name = user.name;
        userInfo.value.nickname = user.nickname;
        toastState.state.show = true;
        toastState.state.msg = '修改成功';
        toastState.state.type = 'success';
      });
    }
  }
};

const uploadAvatar = (filePath: string) => {
  Taro.uploadFile({
    url: getRequestUrl('/admin/user/uploadAvatar'),
    filePath,
    name: 'file',
    header: { Authorization: localStg.get('token') },
    success(res) {
      showSuccessMsg('上传成功');
      const parse = JSON.parse(res.data);
      userInfo.value.avatar = parse.data.imagePath;
    },
    fail() {
      showErrorMsg('上传失败');
    }
  });
};

const avatarState = {
  state: reactive({
    show: false
  }),
  methods: {
    onAvatar() {
      if (userInfo.value.avatar) {
        return;
      }
      avatarState.state.show = true;
    },
    onUseWxAvatar() {
      avatarState.state.show = false;
      Taro.getUserProfile({
        desc: '用于完善用户资料',
        success(result) {
          const user = {
            id: userInfo.value.id,
            name: userInfo.value.name,
            username: userInfo.value.username,
            nickname: userInfo.value.nickname,
            phoneNumber: userInfo.value.phoneNumber
          } as Auth.UserInfo;
          user.avatar = result.userInfo.avatarUrl;
          updateUser(user).then(() => {
            userInfo.value.avatar = result.userInfo.avatarUrl;
            toastState.state.show = true;
            toastState.state.msg = '设置成功';
            toastState.state.type = 'success';
          });
        }
      });
    },
    onUploadAvatar() {
      Taro.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success(result) {
          uploadAvatar(result.tempFilePaths[0]);
        }
      });
    }
  }
};
</script>

<template>
  <basic-layout :show-tab-bar="false">
    <custom-nav-bar left-show title="修改信息" />
    <div class="w-375px text-30px text-primary bg-#fafafa">
      <nut-cell-group title="微信信息">
        <nut-cell is-link title=" " @click="avatarState.methods.onAvatar">
          <template #icon>
            <nut-avatar size="large">
              <template #default>
                <img
                  v-if="userInfo.avatar"
                  alt=""
                  :src="
                    userInfo.avatar.startsWith('http') ? userInfo.avatar : getRequestUrl('/admin' + userInfo.avatar)
                  "
                />
                <span v-else class="text-20px font-bold">{{ userInfo.name.substring(0, 1) }}</span>
              </template>
            </nut-avatar>
          </template>
        </nut-cell>
        <nut-cell
          title="昵称"
          :desc="userInfo.nickname ? userInfo.nickname : ' '"
          is-link
          @click="userState.methods.onUpdate('nickname')"
        ></nut-cell>
      </nut-cell-group>
      <nut-cell-group title="用户信息">
        <nut-cell title="姓名" :desc="userInfo.name" is-link @click="userState.methods.onUpdate('name')"></nut-cell>
        <nut-cell
          title="电话"
          :desc="userInfo.phoneNumber ? userInfo.phoneNumber : ' '"
          is-link
          @click="toastState.methods.cellClick('warn', '暂不支持电话修改')"
        ></nut-cell>
        <nut-cell
          title="家庭ID"
          :desc="userInfo.familyId"
          is-link
          @click="toastState.methods.cellClick('warn', '家庭ID不支持修改')"
        ></nut-cell>
      </nut-cell-group>
      <nut-popup
        v-model:visible="userState.state.show"
        position="bottom"
        round
        closeable
        :style="{ height: '30%' }"
        safe-area-inset-bottom
        @closed="userState.methods.onClosed()"
      >
        <div class="color-#666 text-16px flex-center pt-20px">修改{{ userState.state.inputLabel }}</div>
        <div class="pt-30px">
          <nut-space direction="vertical" fill :gutter="20">
            <nut-input v-model="userState.state.value" placeholder=" " :border="false" />
            <nut-button plain block class="hoo-btn hoo-btn--confirm" @click="userState.methods.onSubmit">
              提交
            </nut-button>
          </nut-space>
        </div>
      </nut-popup>
      <nut-popup
        v-model:visible="avatarState.state.show"
        position="bottom"
        round
        safe-area-inset-bottom
        :style="{ height: '20%' }"
      >
        <nut-space direction="vertical" gutter="20px" class="mt-30px w-100%">
          <nut-button block class="choose-btn" @click="avatarState.methods.onUseWxAvatar">使用微信头像</nut-button>
          <nut-button block class="choose-btn" @click="avatarState.methods.onUploadAvatar">上传头像</nut-button>
        </nut-space>
      </nut-popup>
      <nut-toast v-model:visible="toastState.state.show" :msg="toastState.state.msg" :type="toastState.state.type" />
    </div>
  </basic-layout>
</template>

<style lang="scss">
@import '@/styles/custom';
.choose-btn {
  width: 60%;
  margin: 0 auto;
  border-radius: 8px;
  border-color: #f1f3f5;
  background-color: #f1f3f5;
  color: #666666;
}
</style>
